package com.le.buddha.controller;

import cn.hutool.core.util.StrUtil;
import com.le.buddha.common.BusinessRuntimeException;
import com.le.buddha.common.Response;
import com.le.buddha.conf.ThreadPoolConfig;
import com.le.buddha.conf.UserUtil;
import com.le.buddha.service.IVoiceService;
import com.le.buddha.websocket.MessageHandle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author guole
 * @created 2025/3/25
 */
@Slf4j
@RestController
@RequestMapping("app/send")
public class AppSendController {
    @Resource
    private IVoiceService voiceService;
    @Resource
    private MessageHandle messageHandle;

    @Resource
    private ThreadPoolConfig threadPoolConfig;

    @PostMapping("/sendVoice")
    public Response   sendVoice(HttpServletRequest request, @RequestParam("audioFile") MultipartFile file) {

        String message = "";
        try {
            byte[] bytes = file.getBytes();
            String token = UserUtil.getToken(request);
            message = voiceService.speechToText(bytes);

            if (StrUtil.isNotEmpty(message)) {

                String finalMessage = message;
                threadPoolConfig.threadPoolTaskExecutor().execute(new Runnable() {
                    @Override
                    public void run() {
                        messageHandle.handle(token, finalMessage);

                    }

                });
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessRuntimeException("500", "上传失败");
        }
        return Response.success(message);
    }
}
